import loadingHtml from './loading.html';

export { };

/**
 * 资源监控器
 * 主要用于拦截页面中的 script 和 link 标签，使用 XMLHttpRequest 进行加载，并监听加载进度。
 */
class ResourceMonitor { 

  private _isloading: boolean = true; // 是否正在加载资源
  private _totalResources: number = 0; // 总资源数
  private _loadedResources: number = 0; // 已加载资源数

  public constructor() {
    this.init();
  }

  private init() { 

    this._isloading = true; 
    
    // 渲染loading界面
    document.body.insertAdjacentHTML('afterbegin', loadingHtml.toString()); 
    
    // 获取已加载资源数 link 和 script 标签
    const loadedScripts = document.querySelectorAll('script');
    const loadedLinks = document.querySelectorAll('link');
    this._loadedResources = loadedScripts.length + loadedLinks.length;
    this._totalResources = this._loadedResources;

    // 监听获取动态加载资源个数
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (node.nodeType === 1 && ((node as HTMLElement).tagName === 'SCRIPT' || (node as HTMLElement).tagName === 'LINK')) {
            this._totalResources++;
            this.resourceLoaded();
          }
        });
      });
    })
     
    window.addEventListener('load', () => {
       this._isloading = false;
      console.log('资源加载完成'+new Date().toISOString());
      const mask = document.getElementById('rsc_loading');
      if (mask) {
        mask.remove();
      }
    });

    // 监听资源加载完成事件
    this.resourceLoaded();

    // 加载失败处理
    window.addEventListener('error', (event) => {
      if (event.target && ((event.target as HTMLElement).tagName === 'SCRIPT' || (event.target as HTMLElement).tagName === 'LINK')) {
        this.resourceLoaded();
      } 
    }, true);

    // 计算页面中的资源总数
    this._totalResources = document.querySelectorAll('script, link').length;
    this.updateProgress(0);
  }

  /**
   * 更新加载进度
   * @param progress 进度值 (0-100)
   */
  private updateProgress(progress: number) {
    const progressBar = document.getElementById('loading-progress');
    const progressText = document.getElementById('loading-text');
    
    if (progressBar && progressText) {
      progressBar.style.width = `${progress}%`;
      progressText.textContent = `${Math.round(progress)}%`;
    }
  }

  /**
   * 增加已加载资源计数并更新进度
   */
  public resourceLoaded() {
    this._loadedResources++;
    const progress = (this._loadedResources / this._totalResources) * 100;
    this.updateProgress(progress);
  }

}

// 初始化监控器
const monitor = new ResourceMonitor(); 
(window as any).resourceMonitor = monitor; // 暴露到全局

